package com.mcxx.modules.minimumliving.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mcxx.common.exception.BizException;
import com.mcxx.constant.DictConstant;
import com.mcxx.convert.ApplyConvert;
import com.mcxx.modules.minimumliving.service.FiscalAbutmentService;
import com.mcxx.modules.minimumliving.service.SalvationApplyService;
import com.mcxx.modules.base.service.read.AreaReadService;
import com.mcxx.modules.base.service.read.BankMappingReadService;
import com.mcxx.modules.base.service.read.DictionaryReadService;
import com.mcxx.modules.base.service.read.RuleEngineReadService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.filemanage.file.service.impl.FileServiceImpl;
import com.mcxx.modules.miniSalvation.check.service.read.CheckReadService;
import com.mcxx.modules.miniSalvation.check.service.write.CheckWriteService;
import com.mcxx.modules.miniSalvation.family.dto.*;
import com.mcxx.modules.miniSalvation.family.entity.*;
import com.mcxx.modules.miniSalvation.family.service.read.*;
import com.mcxx.modules.miniSalvation.family.service.write.*;
import com.mcxx.modules.miniSalvation.order.dto.OrderInHouseDTO;
import com.mcxx.modules.miniSalvation.order.dto.OrderStateVerifyDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderEntity;
import com.mcxx.modules.miniSalvation.order.service.read.*;
import com.mcxx.modules.miniSalvation.order.service.write.InHouseWriteService;
import com.mcxx.modules.miniSalvation.order.service.write.IncomeCalculateWriteService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderCertWriteService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderWriteService;
import com.mcxx.modules.miniSalvation.salary.service.read.FamilyMemberSalaryReadService;
import com.mcxx.modules.miniSalvation.salary.service.write.FamilySalaryWriteService;
import com.mcxx.result.BaseResult;
import com.mcxx.util.*;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import com.yinhai.ta404.core.utils.UUIDUtils;
import com.yinhai.ta404.module.dict.entity.TaDictPo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service("salvationApplyService")
@TaTransactional
public class SalvationApplyServiceImpl extends BaseService implements SalvationApplyService {
    @Autowired
    private FamilyMainWriteService familyMainWriteService;
    @Autowired
    private FamilyMemberReadService familyMemberReadService;
    @Autowired
    private FamilyMemberWriteService familyMemberWriteService;
    @Autowired
    private FamilyMemberSalaryReadService memberSalaryReadService;
    @Autowired
    private OrderReadService orderReadService;
    @Autowired
    private OrderWriteService orderWriteService;
    @Autowired
    private MemberAssetsReadService memberAssetsReadService;
    @Autowired
    private MemberAssetsWriteService memberAssetsWriteService;
    @Autowired
    private OrderCertReadService orderCertReadService;
    @Autowired
    private InHouseWriteService inHouseWriteService;
    @Autowired
    private RuleEngineReadService ruleEngineReadService;
    @Autowired
    private FileService fileService;
    @Autowired
    private FamilyMainReadService familyMainReadService;
    @Autowired
    private FamilySupportReadService familySupportReadService;
    @Autowired
    private SpecialPeopleReadService specialPeopleReadService;
    @Autowired
    private MemberAssetsReadService memberAssetsReadServicel;
    @Autowired
    private DictionaryReadService dictionaryReadService;
    @Autowired
    private BlacklistReadService blacklistReadService;
    @Autowired
    private IncomeCalculateReadService incomeCalculateReadService;
    @Autowired
    private AreaReadService areaReadService;
    @Autowired
    private BankMappingReadService bankMappingReadService;
    @Autowired
    private BankWriteService bankWriteService;
    @Autowired
    private FiscalAbutmentService fiscalAbutmentService;
    @Autowired
    private CheckReadService checkReadService;
    @Autowired
    private FamilyMemberHistoryReadService familyMemberHistoryReadService;
    @Autowired
    private OrderCertWriteService orderCertWriteService;
    @Autowired
    private FamilySupportWriteService familySupportWriteService;
    @Autowired
    private SpecialPeopleWriteService specialPeopleWriteService;
    @Autowired
    private InHouseReadService inHouseReadService;
    @Autowired
    private FamilySalaryWriteService familySalaryWriteService;
    @Autowired
    private IncomeCalculateWriteService incomeCalculateWriteService;
    @Autowired
    private CheckWriteService checkWriteService;
    @Value("${society.template.dir:bakhtml}")
    private String backUpDir;
    @Value("${society.template.minifilename:minibackup.html}")
    private String backUpMiniFileName;
    @Value("${society.template.exfilename:exbackup.html}")
    private String backUpExFileName;
    private final  String separator = System.getProperty("file.separator");
    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);




    public ApplyRtnDTO saveSalvationRequest(MininumLivingApplyDTO applyDto, UserAccountVo accountVo){


        List<FamilyMemberEntity> memberLists = familyMemberReadService.listNormalMemberByFamilyId(applyDto.getFamilyId());
        if(CollectionUtils.isNotEmpty(memberLists)){
            List<String> list = new ArrayList<>();
            for(FamilyMemberEntity memberList : memberLists){
                list.add(memberList.getIdcard());
            }
            List<String> names = blacklistReadService.cntByIdcards(list);
            if(org.apache.commons.collections.CollectionUtils.isNotEmpty(names)){
                throw  new BizException("-1","当前家庭成员【" + String.join(",", names) + "】在黑名单中");
            }

        }

        if(CommonUtil.invalidArgs(applyDto.getOrderId())){

            if(Constant.DomesticRelation.ONESELF.equals(applyDto.getFamilyRelation())){
                logger.info("如果申请人就是户主，参数是：{}", applyDto);
                applyDto.setName(applyDto.getApplyName());
                applyDto.setIdcard(applyDto.getApplyIdcard());
            }
      }else{

            FamilyMemberEntity masertInfo = familyMemberReadService.getMasertInfo(applyDto.getFamilyId());
            if(!CommonUtil.invalidArgs(masertInfo)){
                logger.info("更新的时候,查询户主的member信息，参数是：{}", applyDto);
                applyDto.setMemberId(masertInfo.getId());
                applyDto.setName(masertInfo.getName());
                applyDto.setIdcard(masertInfo.getIdcard());
            }
        }

        FamilyMainEntity familyMainEntity = ApplyConvert.convertToFamilyMainEntity(applyDto, accountVo);
        FamilyMemberEntity memberEntity = ApplyConvert.convertToFamilyMemberEntity(applyDto, accountVo);


        if (Constant.OrderType.NEW.equals(applyDto.getType())) {
            memberSalaryReadService.checkMemberIsSaved(applyDto.getOrderId(), memberEntity.getId(), DateUtil.getMonthString());
        }

        if(StringUtils.isEmpty(applyDto.getOrderId())&&StringUtils.isNotEmpty(applyDto.getFamilyId())){
           familyMemberWriteService.updateNoSave(applyDto.getFamilyId());
        }

        ApplyRtnDTO applyRtnDTO = familyMainWriteService.addFamilyAndMember4Apply(familyMainEntity, memberEntity, applyDto.getMemberOldState(), accountVo,applyDto.getType());


        OrderEntity orderEntity = this.saveOrder(applyDto, applyRtnDTO, accountVo);



        applyRtnDTO.setOrderId(orderEntity.getOrderId());
        applyRtnDTO.setStandType(applyDto.getStandType());
        applyRtnDTO.setOrderBizState(orderEntity.getBizState());
        return applyRtnDTO;
    }


    @Override
    public ApplyRtnDTO addSalvationRequest(MininumLivingApplyDTO applyDto, UserAccountVo accountVo) throws BizException {

        return this.saveSalvationRequest(applyDto, accountVo);
    }


    @Override
    public int modifyOrder(OrderEntity orderEntity) throws BizException {
        return orderWriteService.updateIgnoreNull(orderEntity);
    }


    @Override
    public ApplyRtnDTO modifySalvationRequest(MininumLivingApplyDTO applyDto, UserAccountVo accountVo,String channel) throws BizException {

        this.isCanEditOrder(applyDto, accountVo);


        this.verifyFamilyMasterNum(applyDto.getFamilyId());


        this.verifyApplyMaster(applyDto);

        this.verifyMemberAssets(applyDto.getOrderId());

        this.verifyfamilyRevenue(applyDto.getFamilyId());


        this.verifySupportAuthor(applyDto.getFamilyId(),applyDto.getOrderId());



        this.verifyCompleteMemberInfo(applyDto.getFamilyId(),applyDto.getStandType());


        this.verifyCert(applyDto.getOrderId(), applyDto.getFamilyId(),channel);


        ApplyRtnDTO applyRtnDTO = this.saveSalvationRequest(applyDto, accountVo);


        String inHouseId = this.saveOrderInHouse(applyDto, accountVo);
        applyRtnDTO.setOrderInhouseId(inHouseId);

        this.updateBankPhone(applyDto,applyRtnDTO.getMemberId());
        return applyRtnDTO;
    }


    @Override
    public ApplyRtnDTO houseHoldCancelSave(MininumLivingApplyDTO applyDto, UserAccountVo accountVo) throws BizException {

        this.isCanEditOrder(applyDto, accountVo);


        this.verifyFamilyMasterNum(applyDto.getFamilyId());


        this.verifyApplyMaster(applyDto);

//        this.verifyMemberAssets(applyDto.getOrderId());

//        this.verifySupportAuthor(applyDto.getFamilyId(),applyDto.getOrderId());


        this.verifyCompleteMemberInfo(applyDto.getFamilyId(),applyDto.getStandType());


//        this.verifyCert(applyDto.getOrderId(), applyDto.getFamilyId());


        ApplyRtnDTO applyRtnDTO = this.saveSalvationRequest(applyDto, accountVo);


        String inHouseId = this.saveOrderInHouse(applyDto, accountVo);
        applyRtnDTO.setOrderInhouseId(inHouseId);
        return applyRtnDTO;
    }


    public void verifySupportAuthor(String familyId,String orderId){

        int counts = orderCertReadService.selectSupportInfo(familyId);
        if(counts>0){
            throw new BizException("-1","当前家庭有赡(抚扶)养人信息未完善，请完善后再继续操作");
        }
        int count = orderCertReadService.selectSupportAuthor(familyId,orderId);
        if(count>0){
            throw new BizException(FailureCode.ERR_20085);
        }
    }


    public void isCanEditOrder(MininumLivingApplyDTO applyDto, UserAccountVo userAccountVo){

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(applyDto.getOrderId());

        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.ORDER_EDIT, orderStateVerifyDTO, userAccountVo);
    }


    public OrderEntity saveOrder(MininumLivingApplyDTO applyDto, ApplyRtnDTO applyRtnDTO, UserAccountVo accountVo){

        applyDto.setFamilyId(applyRtnDTO.getFamilyId());

        if(CommonUtil.invalidArgs(applyDto.getMemberId()) &&  Constant.DomesticRelation.ONESELF.equals(applyDto.getFamilyRelation()) ){
            applyDto.setMemberId(applyRtnDTO.getMemberId());
        }
        OrderEntity orderEntity = ApplyConvert.convertToOrderEntity(applyDto, accountVo);
        orderEntity.setBusinessType(Constant.BusinessCode.DIBAO);


        if (StringUtils.isEmpty(applyDto.getOrderId())) {

            orderEntity.setOrderId(IdUtil.simpleUUID());
            orderEntity.setState(Constant.BizState.SALVATION);
            orderEntity.setWoaState(Constant.WOASTATE.UNPROCESSED);
            orderEntity.setBizState(Constant.BizState.SALVATION);
            orderWriteService.insertIgnoreNull(orderEntity);


            if(Constant.MinimumLivingType.SINGLE.equals(applyDto.getFamilyObjectType())){
                if(Constant.OrderType.NEW.equals(applyDto.getType())){
                    MemberCardRtnDTO  memberCardRtn = familyMemberHistoryReadService.queryLowerMemberHistoryByCardId(applyDto.getApplyIdcard());
                    if(memberCardRtn != null){

                        int check = checkWriteService.copyCheckInfo(memberCardRtn.getOrderId(),orderEntity.getOrderId());

                        // int inHouse = inHouseWriteService.copyInHouseInfo(memberCardRtn.getOrderId(),orderEntity.getOrderId());
                        OrderInHouseDTO orderInHouseDTO = inHouseReadService.queryNewByOrderId(memberCardRtn.getOrderId(),"4");
                        if(null != orderInHouseDTO){
                            String inHouseId = IdUtil.simpleUUID();
                            inHouseWriteService.copyInHouseInfo(orderInHouseDTO.getId(),inHouseId,orderEntity.getOrderId());
                            orderCertWriteService.copyInHouseCertInfo(orderInHouseDTO.getId(),inHouseId,orderEntity.getOrderId());
                        }





                        memberAssetsWriteService.copyMemberAssetsInfo(memberCardRtn.getOrderId(),orderEntity.getOrderId());


                        incomeCalculateWriteService.backupCalculate(memberCardRtn.getOrderId(),orderEntity.getOrderId());


                        int material = orderCertWriteService.copyCertInfo(memberCardRtn.getOrderId(),orderEntity.getOrderId());

//                            orderEntity.setState(Constant.BizStateNew.YES_IN_HOUSE);
//                            orderEntity.setBizState(Constant.BizStateNew.YES_IN_HOUSE);



                    }
                }
            }
        } else {
            if(!CommonUtil.invalidArgs(applyDto.getOrderBizState())){
                orderEntity.setBizState(applyDto.getOrderBizState());
            }
            if(!CommonUtil.invalidArgs(applyDto.getOrderState())){
                orderEntity.setState(applyDto.getOrderState());
            }

            orderWriteService.updateIgnoreNull(orderEntity);
        }
        return orderEntity;
    }


    public String saveOrderInHouse(MininumLivingApplyDTO applyDto, UserAccountVo userAccountVo) {

        if(CommonUtil.invalidArgs(applyDto.getCheckPeople()) || CommonUtil.invalidArgs(applyDto.getCheckDate())
                || CommonUtil.invalidArgs(applyDto.getCheckContent())){

            return null;
        }


        OrderInHouseDTO inHouseDTO = ApplyConvert.convertToInhouseEntity(applyDto);


        if(CommonUtil.invalidArgs(inHouseDTO.getId())){
            inHouseWriteService.addInHouse(inHouseDTO, applyDto.getInhouseCertIdList(), userAccountVo);
        }else{
            inHouseWriteService.updateById(inHouseDTO, applyDto.getInhouseCertIdList(), userAccountVo);
        }
        return inHouseDTO.getId();
    }

    public void updateBankPhone(MininumLivingApplyDTO applyDTO,String memberId){
        if(Constant.DomesticRelation.ONESELF.equals(applyDTO.getFamilyRelation())&&StringUtils.isNotEmpty(memberId)){
            BankEntity entity = new BankEntity();
            entity.setFamilyId(applyDTO.getFamilyId());
            entity.setMemberId(memberId);
            entity.setAgentBankPhone(applyDTO.getPhone());
            bankWriteService.updateBankPhone(entity);
        }
    }

    @Override
    public ApplyRtnDTO tempSaveInHouse(MininumLivingApplyDTO applyDto, UserAccountVo accountVo,String channel) {

        this.isCanTempSaveInHouse(applyDto, accountVo);


        this.verifyFamilyMasterNum(applyDto.getFamilyId());


        this.verifyMemberAssets(applyDto.getOrderId());


        this.verifySupportAuthor(applyDto.getFamilyId(),applyDto.getOrderId());


        this.verifyCompleteMemberInfo(applyDto.getFamilyId(),applyDto.getStandType());


        this.verifyCert(applyDto.getOrderId(), applyDto.getFamilyId(),channel);


        ApplyRtnDTO applyRtnDTO = this.saveSalvationRequest(applyDto, accountVo);


        String inHouseId = this.saveOrderInHouse(applyDto, accountVo);
        applyRtnDTO.setOrderInhouseId(inHouseId);


        return applyRtnDTO;
    }


    public void isCanTempSaveInHouse(MininumLivingApplyDTO applyDto, UserAccountVo accountVo){


        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(applyDto.getOrderId());


        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.START_TOWN_IN_HOUSE, orderStateVerifyDTO, accountVo);


        applyDto.setOrderBizState(orderStateVerifyDTO.getNextBizState());
    }


    @Override
    public ApplyRtnDTO completeInHouse(MininumLivingApplyDTO applyDto, UserAccountVo accountVo,String channel) {

        this.isCanCompleteInHouse(applyDto, accountVo);


        this.verifyFamilyMasterNum(applyDto.getFamilyId());

        this.verifySupportAuthor(applyDto.getFamilyId(),applyDto.getOrderId());


        this.verifyMemberAssets(applyDto.getOrderId());


        this.verifyCompleteMemberInfo(applyDto.getFamilyId(),applyDto.getStandType());


        this.verifyOrderInHouse(applyDto);


        this.verifyCert(applyDto.getOrderId(), applyDto.getFamilyId(),channel);


        ApplyRtnDTO applyRtnDTO = this.saveSalvationRequest(applyDto, accountVo);


        String inHouseId = this.saveOrderInHouse(applyDto, accountVo);
        applyRtnDTO.setOrderInhouseId(inHouseId);


        return applyRtnDTO;
    }


    public void isCanCompleteInHouse(MininumLivingApplyDTO applyDto, UserAccountVo userAccountVo){


        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(applyDto.getOrderId());

        orderStateVerifyDTO.setNextCondition("1");


        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.COMPLETE_TOWN_IN_HOUSE, orderStateVerifyDTO, userAccountVo);


        applyDto.setOrderBizState(orderStateVerifyDTO.getNextBizState());
        applyDto.setOrderState(orderStateVerifyDTO.getNextState());
    }




    @Override
    public String modifyFamilyHolder(String familyId, String idcard, UserAccountVo accountVo) {
        FamilyMemberEntity memberStat = familyMemberReadService.getMemberStateByCardId(idcard);
        if (Constant.PeopleState.NORMAL.equals(memberStat.getState())) {

            return memberStat.getFamilyId();
        }
        FamilyMainEntity familyEntity=new FamilyMainEntity();

        familyEntity.setId(Constant.getUUID());

        familyEntity.setFamilyNumber(1);

        familyEntity.setAreaCode(accountVo.getAreaCode());

        familyMainWriteService.addFamily(familyEntity);

        familyMemberWriteService.changeFamilyId(familyId,idcard,familyEntity.getId());

        return familyEntity.getId();
    }




    @Override
    public double saveMemberAssets(MemberAssetsEntity entity, UserAccountVo userAccountVo) {

        memberAssetsReadService.cntMemberAssetsNotProperty(entity);


        if(CommonUtil.invalidArgs(entity.getId())){
            memberAssetsWriteService.insertIgnoreNull(entity, userAccountVo);
        }else{
            memberAssetsWriteService.updateIgnoreNull(entity);
        }


        double familyRevenue = familyMemberWriteService.updateFamilyRevenue(entity);

        return familyRevenue;
    }


    @Override
    public double saveMemberIncome(List<JSONObject> entityList, String orderId, String familyId, UserAccountVo userAccountVo,MemberAssetsDTO memberAssetsDTO) {

        double familyRevenue = 0.0;
        memberAssetsWriteService.deleteByOrderId(orderId);
        MemberAssetsEntity assetsEntity = new MemberAssetsEntity();
        assetsEntity.setOrderId(orderId);
        assetsEntity.setFamilyId(familyId);
        assetsEntity.setQuote(0d);
        if(StringUtils.isNotEmpty(memberAssetsDTO.getIncomeRemark())){
            assetsEntity.setAssetsType(Constant.MemberAssetsType.SHOU_RU_BEIZHU);
            assetsEntity.setDescription(memberAssetsDTO.getIncomeRemark());
            memberAssetsWriteService.insertIgnoreNull(assetsEntity, userAccountVo);
        }
        if(StringUtils.isNotEmpty(memberAssetsDTO.getAssetsRemark())){
            assetsEntity.setAssetsType(Constant.MemberAssetsType.ZHICHU_BEIZHU);
            assetsEntity.setDescription(memberAssetsDTO.getAssetsRemark());
            memberAssetsWriteService.insertIgnoreNull(assetsEntity, userAccountVo);
        }
        if(!CollectionUtils.isEmpty(entityList)){
            String isExpendHard = Constant.IsExpendHard.NO;
            for(JSONObject m: entityList){
                MemberAssetsEntity entity = JSONObject.toJavaObject(m,MemberAssetsEntity.class);
                entity.setOrderId(orderId);
                entity.setFamilyId(familyId);
                int i = memberAssetsWriteService.insertIgnoreNull(entity, userAccountVo);
                if(i <= 0){
                    throw new BizException("-1","保存家庭经济信息失败");
                }

                familyRevenue = familyMemberWriteService.updateFamilyRevenue(entity);
                String assetsType = entity.getAssetsType();
                if(Constant.IsExpendHard.NO.equals(isExpendHard) && assetsType.length()>=2 && "02".equals(assetsType.substring(0,2))){
                    isExpendHard = Constant.IsExpendHard.YES;
                }
            }
            FamilyMainEntity entity = new FamilyMainEntity();
            entity.setId(familyId);
            entity.setIsExpendHard(isExpendHard);
            familyMainWriteService.updateFamily(entity);
        }else {

            FamilyMainEntity familyMainEntity = new FamilyMainEntity();
            familyMainEntity.setId(familyId);
            familyMainEntity.setFamilyRevenue(familyRevenue);
            int rst = familyMainWriteService.updateFamily(familyMainEntity);
        }
        return familyRevenue;
    }


    @Override
    public double deleteMemberAssets(MemberAssetsEntity entity) {

        memberAssetsWriteService.deleteById(entity.getId());

        double familyRevenue = familyMemberWriteService.updateFamilyRevenue(entity);

        return familyRevenue;
    }






    @Override
    public void verifyMemberAssets(String orderId){

        int count =  orderReadService.selectOrderInCalculate(orderId);
        if(count<1){

            int rst = memberAssetsReadService.cntOrderAssets(orderId);
            if(rst <= 0){
                throw new BizException(FailureCode.ERR_20068);
            }
        }else{

            int rst = incomeCalculateReadService.selectCountByOrderId(orderId);
            if(rst<=0){
                throw new BizException(FailureCode.ERR_20087);
            }
        }
    }


    public void verifyFamilyMasterNum(String familyId){
        int rst = familyMemberReadService.cntFamilyMaster(familyId);
        if(rst > 1){
            throw new BizException(FailureCode.ERR_10080);
        }
        if(rst == 0){
            throw new BizException(FailureCode.ERR_10081);
        }
    }


    @Override
    public void verifyfamilyRevenue(String familyId){
        String familyRevenue = familyMainReadService.selectFamilyRevenue(familyId);
        if(StringUtils.isEmpty(familyRevenue)){
            throw new BizException("-1","家庭人均月收入为空，请重新编辑家庭经济情况");
        }
    }


    public void verifyApplyMaster(MininumLivingApplyDTO applyDto){
        String masterIdCard = familyMemberReadService.getMasterIdCardByFamilyId(applyDto.getFamilyId());

        if(StringUtils.isNotEmpty(masterIdCard) && masterIdCard.equals(applyDto.getApplyIdcard())&&!Constant.DomesticRelation.ONESELF.equals(applyDto.getFamilyRelation())){
            throw new BizException(FailureCode.ERR_20004);
        }

        if(Constant.DomesticRelation.ONESELF.equals(applyDto.getFamilyRelation())){
            if(StringUtils.isNotEmpty(masterIdCard) && !masterIdCard.equals(applyDto.getApplyIdcard())){
                throw new BizException(FailureCode.ERR_20004);
            }
        }
    }


    @Override
    public void verifyCompleteMemberInfo(String familyId){
        String rst = familyMemberReadService.cntCompleteInfoNum(familyId, Constant.BusinessCode.DIBAO,null);

        if(!CommonUtil.invalidArgs(rst)){
            throw new BizException(FailureCode.ERR_20067);
        }
    }

    @Override
    public void verifyCompleteMemberInfo(String familyId,String standType){
        String rst = familyMemberReadService.cntCompleteInfoNum(familyId, Constant.BusinessCode.DIBAO,standType);

        if(!CommonUtil.invalidArgs(rst)){
            throw new BizException(FailureCode.ERR_20067);
        }
    }


    @Override
    public void verifyExpireCheck(String orderId){
        int count = checkReadService.selectExpireRecord(orderId);

        if(count<1){
            throw new BizException(FailureCode.ERR_20088);
        }
    }


    public void verifyOrderInHouse(MininumLivingApplyDTO applyDto){

        if(CommonUtil.invalidArgs(CommonUtil.invalidArgs(applyDto.getCheckPeople()) || CommonUtil.invalidArgs(applyDto.getCheckDate())
                || CommonUtil.invalidArgs(applyDto.getCheckContent()))){
            throw new BizException(FailureCode.ERR_20014);
        }


        if(CollectionUtils.isNotEmpty(applyDto.getInhouseCertIdList())){

            return;
        }

        int rst = orderCertReadService.cntInhouseCertNum(applyDto.getOrderId(), applyDto.getOrderInhouseId());
        if(rst <= 0){
            throw new BizException("-1", "当前家庭没有上传【入户调查辅证材料】，请上传！");
        }
    }


    public void verifyCert(String orderId, String familyId,String channel){

        int rst = familyMemberReadService.cntFamilyMember(familyId);
        if(rst<1){
            Map<String, Long>  cntMap = orderCertReadService.cntFamilyCertNum(orderId, familyId);

            if(cntMap.containsKey("familyRegisterNum") && cntMap.get("familyRegisterNum") <= 0){
                throw new BizException("-1", "当前家庭没有上传【户口本】资料，请上传！");
            }

            if(cntMap.containsKey("checkAuthorizationNum") && cntMap.get("checkAuthorizationNum") <= 0){
                throw new BizException("-1", "当前家庭没有上传【救助申请家庭经济状况核对授权书】，请上传！");
            }

            if(StringUtils.isBlank(channel)  && cntMap.containsKey("checkfamilyIntegrityNum") && cntMap.get("checkfamilyIntegrityNum") <= 0){
                throw new BizException("-1", "当前家庭没有上传【救助申请家庭诚信承诺书】，请上传！");
            }

            List<String> memberIdcardNumMap = orderCertReadService.cntMemberIdcardNum(orderId, familyId);
            if(CollectionUtils.isNotEmpty(memberIdcardNumMap)){
                throw new BizException("-1", "当前成员【" + String.join(",", memberIdcardNumMap) + "】没有上传身份证，请先上传身份证");
            }
        }

        List<String> supportNoIdCardName = orderCertReadService.cntSupportIdCardNum(orderId, familyId);
        if(CollectionUtils.isNotEmpty(supportNoIdCardName)){
            throw new BizException("-1", "当前赡抚养人【" + String.join(",", supportNoIdCardName) + "】没有上传身份证，请先上传身份证");
        }
    }


    @Override
    public  List<String> verifyMemberAssetsList(Map<String, String> orderIdIdcardMap){

        List<String> orderIdList = new ArrayList<>(orderIdIdcardMap.keySet());

        List<MemberAssetsDTO> memberAssetsDTOList = memberAssetsReadService.cntOrderAssetsList(orderIdList);
        Map<String, Integer> memberAssetsNumMap = memberAssetsDTOList.stream().collect(Collectors.toMap(MemberAssetsDTO::getOrderId, MemberAssetsDTO::getAssetsNum));


        List<String> noExistsAssestsIdcard = new ArrayList<>();
        orderIdList.forEach(orderId->{
            if(!memberAssetsNumMap.containsKey(orderId) || memberAssetsNumMap.get(orderId) == 0){

                noExistsAssestsIdcard.add(orderIdIdcardMap.get(orderId));
            }
        });
        return noExistsAssestsIdcard;
    }


    @Override
    public List<String> verifyFamilyMasterNum(Map<String, String> familyIdIdcardMap){

        List<String> familyIdList =  new ArrayList<>(familyIdIdcardMap.keySet());

        List<String> masterNumOneList = familyMemberReadService.cntFamilyMasterErrorList(familyIdList);

        List<String> masterNumErrorIdcard = new ArrayList<>();
        masterNumOneList.forEach(familyId -> {
            masterNumErrorIdcard.add(familyIdIdcardMap.get(familyId));
        });
        return masterNumErrorIdcard;
    }


    @Override
    public List<String> verifyCompleteMemberInfo(Map<String, String> familyIdIdcardMap){

        List<String> familyIdList =  new ArrayList<>(familyIdIdcardMap.keySet());

        List<String> infoNoCompList = familyMemberReadService.cntCompleteInfoNumList(familyIdList);

        List<String> memberInfoNoCompleteIdcard = new ArrayList<>();
        infoNoCompList.forEach(familyId -> {
            memberInfoNoCompleteIdcard.add(familyIdIdcardMap.get(familyId));
        });
        return memberInfoNoCompleteIdcard;
    }



    @Override
    public String backupHtml(String orderId,String familyId,String businessCode) {


        this.verifyFamilyMasterNum(familyId);





        this.verifyCompleteMemberInfo(familyId);


        InputStream htmlInputStream = null;
        if(Constant.BusinessCode.DIBAO.equals(businessCode)){
            htmlInputStream = this.getClass().getResourceAsStream("/"+backUpDir+"/"+backUpMiniFileName);
        }else{
            htmlInputStream = this.getClass().getResourceAsStream("/"+backUpDir+"/"+backUpExFileName);
        }

        FamilyMainBackUpEntity mainEntity = familyMainReadService.selectBackUpInfo(orderId);

        List<FamilyMemberEntity> familyMemberEntities = familyMemberReadService.listNormalMemberByFamilyId(familyId);

        List<FamilySupportEntity> familySupportList = familySupportReadService.getFamilySupportList(familyId);

        List<FamilySpecialEntity> familySpecialList = specialPeopleReadService.getFamilySpecialList(familyId);

        List<MemberAssetsDTO> memberAssetsEntities = memberAssetsReadServicel.queryListByFamilyId(familyId, orderId, "");


        TaDictPo taDictPo = dictionaryReadService.getCodeCache(DictConstant.FM_RELATION,mainEntity.getRelation());
        mainEntity.setRelation(taDictPo.getLabel());

        taDictPo = dictionaryReadService.getCodeCache(DictConstant.CENSUS_TYPE,mainEntity.getCensusType());
        mainEntity.setCensusType(taDictPo.getLabel());

        taDictPo = dictionaryReadService.getCodeCache(DictConstant.POVERTY_FACTORS,mainEntity.getMainreson());
        mainEntity.setMainreson(taDictPo.getLabel());


        for(FamilyMemberEntity memberEntity:familyMemberEntities){

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.FM_RELATION,memberEntity.getFamilyRelation());
            memberEntity.setFamilyRelation(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.EDUCATION_LEVEL,memberEntity.getEducation());
            memberEntity.setEducation(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.HEALTH,memberEntity.getHealthState());
            memberEntity.setHealthState(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.WORK_POWER,memberEntity.getWorkPower());
            memberEntity.setWorkPower(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.Employment_Status,memberEntity.getWorkState());
            memberEntity.setWorkState(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.CENSUS_TYPE,memberEntity.getCensusType());
            memberEntity.setCensusType(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.NATION,memberEntity.getNation());
            memberEntity.setNation(taDictPo.getLabel());

            taDictPo = dictionaryReadService.getCodeCache(DictConstant.SERIOUS_DISEASE,memberEntity.getSeriousDisease());
            memberEntity.setSeriousDisease(taDictPo.getLabel());

            memberEntity.setSex(StringUtils.isBlank(memberEntity.getSex())?"":dictionaryReadService.getCodeCache(DictConstant.SEX,memberEntity.getSex()).getLabel());

            memberEntity.setIsdisability(StringUtils.isBlank(memberEntity.getDisabilityLevel())?"否":"是");

            memberEntity.setDisabilityLevel(StringUtils.isBlank(memberEntity.getDisabilityLevel())?"":dictionaryReadService.getCodeCache(DictConstant.DISABLED_LEVEL,memberEntity.getDisabilityLevel()).getLabel());

            memberEntity.setDisabilityType(StringUtils.isBlank(memberEntity.getDisabilityType())?"":dictionaryReadService.getCodeCache(DictConstant.DISABLE_TYPE,memberEntity.getDisabilityType()).getLabel());

            memberEntity.setIsHelpPoor(StringUtils.isBlank(memberEntity.getIsHelpPoor())?"":dictionaryReadService.getCodeCache(DictConstant.IS_HELP_POOR,memberEntity.getIsHelpPoor()).getLabel());

            memberEntity.setIsAtSchool(StringUtils.isBlank(memberEntity.getIsSaveObject())?"":dictionaryReadService.getCodeCache(DictConstant.IS_AT_SCHOOL,memberEntity.getIsAtSchool()).getLabel());

            memberEntity.setDocHelpPoor(StringUtils.isBlank(memberEntity.getDocHelpPoor())?"":dictionaryReadService.getCodeCache(DictConstant.DOC_HELP_POOR,memberEntity.getDocHelpPoor()).getLabel());

            memberEntity.setSelfcareLevel(StringUtils.isBlank(memberEntity.getSelfcareLevel())?"":dictionaryReadService.getCodeCache(DictConstant.SelfCareAbility,memberEntity.getSelfcareLevel()).getLabel());


            if(StringUtils.isNotBlank(memberEntity.getSelfcareSelect())){
                String[] splitSelect = memberEntity.getSelfcareSelect().split(",");
                StringBuffer sb = new StringBuffer();
                Arrays.asList(splitSelect).stream().forEach(splitString->sb.append(dictionaryReadService.getCodeCache(DictConstant.NEW_SELF,splitString).getLabel()).append(","));
                memberEntity.setSelfcareSelect(sb.toString().substring(0,sb.length()-1));
            }
            memberEntity.setState(StringUtils.isBlank(memberEntity.getState())?"":dictionaryReadService.getCodeCache(DictConstant.SURVIVAL_STATUS,memberEntity.getState()).getLabel());
        }

        for(FamilySupportEntity supportEntity:familySupportList){

            supportEntity.setSex(StringUtils.isBlank(supportEntity.getSex())?"":dictionaryReadService.getCodeCache(DictConstant.SEX,supportEntity.getSex()).getLabel());

            supportEntity.setSupportRelation(StringUtils.isBlank(supportEntity.getSupportRelation())?"":dictionaryReadService.getCodeCache(DictConstant.FM_RELATION,supportEntity.getSupportRelation()).getLabel());

            supportEntity.setSupportInfo(StringUtils.isBlank(supportEntity.getSupportInfo())?"":dictionaryReadService.getCodeCache(DictConstant.SUPPORT_INFO,supportEntity.getSupportInfo()).getLabel());
        }


        for(FamilySpecialEntity specialEntity:familySpecialList){
            specialEntity.setFamilyRelationship(StringUtils.isBlank(specialEntity.getFamilyRelationship())?"":dictionaryReadService.getCodeCache(DictConstant.FM_RELATION,specialEntity.getFamilyRelationship()).getLabel());
        }

        String uuid = UUIDUtils.getUUID();
        File tmpFile = new File(System.getProperty("java.io.tmpdir")+separator +uuid+".html");
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(htmlInputStream));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile)));
            String line = "";
            Gson gson = new GsonBuilder().serializeNulls().create();
            while((line=reader.readLine())!=null){
                writer.write(line);
                writer.newLine();
                if(line.indexOf("<script>")>1){

                    StringBuffer familyBuffer =  new StringBuffer();

                    familyBuffer.append("var familyInfo = ");
                    familyBuffer.append(gson.toJson(mainEntity));
                    writer.write(familyBuffer.toString());
                    writer.newLine();

                    writer.write("var memberDatas=");
                    writer.write(gson.toJson(familyMemberEntities));
                    writer.newLine();

                    writer.write("var supportDatas=");
                    writer.write(gson.toJson(familySupportList));
                    writer.newLine();

                    writer.write("var specialDatas=");
                    writer.write(gson.toJson(familySpecialList));
                    writer.newLine();

                    writer.write("var assetdatas=");
                    writer.write(gson.toJson(memberAssetsEntities));
                    writer.newLine();
                }
            }
            writer.close();
            reader.close();

            FileInputStream input = new FileInputStream(tmpFile);
            String objectKey = fileService.upload(input,tmpFile.getName());

            orderWriteService.updateBackUpFile(objectKey,orderId);

            if(Constant.BusinessCode.DIBAO.equals(businessCode)){

                int count = inHouseReadService.cntByOrderId(orderId,"4");
                if(count>0){
                    OrderEntity orderEntity = new OrderEntity();
                    orderEntity.setOrderId(orderId);
                    orderEntity.setBizState(Constant.BizStateNew.IN_HOUSE_ING);
                    orderWriteService.updateIgnoreNull(orderEntity);
                }
            }

            tmpFile.delete();
            return objectKey;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1","备份发生异常");
        }
    }

    @Override
    public Map<String, String> gainBankInfo(BankAbutmentDTO dto, UserAccountVo userAccountVo) {
        Map<String, String> map = new HashMap<>();
        if(StringUtils.isEmpty(dto.getSsssidcardnum())){
            throw new BizException("-1","身份证号码不能为空");
        }
        if(StringUtils.isEmpty(dto.getSsssobjectname())){
            throw new BizException("-1","姓名不能为空");
        }
        if(StringUtils.isEmpty(dto.getBankcode())){
            throw new BizException("-1","开户银行不能为空");
        }
        if(StringUtils.isEmpty(dto.getAccouttype())){
            throw new BizException("-1","账号类型不能为空");
        }

        if(Constant.FundCapitalType.SOCIAL_SECURITY.equals(dto.getAccouttype())){
            dto.setAccouttype("0");
        }else{
            dto.setAccouttype("1");
        }


        String tenantIdStr = areaReadService.getTenantIdRela(userAccountVo.getOrgId().substring(0,6)+"000000");
        dto.setTenantId(tenantIdStr);

        String bankCode = bankMappingReadService.getFinanceByRescue(dto.getBankcode());
        dto.setBankcode(bankCode);
        dto.setDatasources("01");

        String result = fiscalAbutmentService.fiscalAbutmentInfo(dto);

        if(!StringUtils.isEmpty(result)){
            JSONObject jsonObject = JSONObject.parseObject(result);
            String code = jsonObject.getString("code");

            if("-1".equals(code)){
                throw new BizException("-1","当前补贴对象未绑定银行帐号");
            }else{
                String data = jsonObject.getString("data");
                JSONObject jsonData = JSONObject.parseArray(data).getJSONObject(0);
                String accountnum = jsonData.getString("accountnum");
                map.put("accountnum",accountnum);
            }
        }
        return map;
    }

    public void isCanEditOrder(String orderId, UserAccountVo userAccountVo){

        OrderStateVerifyDTO orderStateVerifyDTO = orderReadService.getBizStateReportFile(orderId);

        ruleEngineReadService.getBizStateRuleThrow(Constant.OrderBizStateType.ORDER_EDIT, orderStateVerifyDTO, userAccountVo);
    }

    @Override
    public void delete(FamilyMemberDTO dto, UserAccountVo accountVo){
        this.isCanEditOrder(dto.getOrderId(),accountVo);
        familyMemberWriteService.delete(dto,accountVo);
    }

    @Override
    public String addFamilyMember(FamilyMemberDTO dto,UserAccountVo accountVo){
        this.isCanEditOrder(dto.getOrderId(),accountVo);
        return  familyMemberWriteService.addFamilyMember(dto,accountVo);
    }

    @Override
    public void  updateFamilyMember(FamilyMemberDTO dto,UserAccountVo accountVo)  {
        if(Constant.DomesticRelation.ONESELF.equals(dto.getFamilyRelation()) && !Constant.PeopleState.NORMAL.equals(dto.getState())
                    && checkifHasNormState(dto.getOrderId())){
            throw new BizException("-1","人员状态不为正常,与户主关系不能置为本人");
        }

        this.isCanEditOrder(dto.getOrderId(),accountVo);
        familyMemberWriteService.updateFamilyMember(dto,accountVo);
    }

    @Override
    public void changeMemberApply(String familyId, String orderId, Map<String,String> relationshipMap,UserAccountVo accountVo){
        this.isCanEditOrder(orderId,accountVo);
        familyMemberWriteService.changeMemberApply(familyId,orderId,relationshipMap);
    }

    @Override
    public int houseHoldSuspend(String orderId,String familyId){

        int i = familyMemberWriteService.updateExpireByFamilyId(familyId);

        OrderEntity entity = new OrderEntity();
        entity.setOrderId(orderId);
        entity.setSaveMemberNumber(0);
        entity.setSalvMoney(0d);
        entity.setBaseSalary(0d);
        orderWriteService.updateIgnoreNull(entity);

        FamilyMainEntity familyMainEntity = new FamilyMainEntity();
        familyMainEntity.setId(familyId);
        familyMainEntity.setSaveMemberNumber(0);
        familyMainWriteService.updateFamily(familyMainEntity);

        familySalaryWriteService.deleteFamilySalaryByOrderId(orderId);
        return i;
    }

    @Override
    public int suspend(String orderId,String familyId){

        OrderEntity entity = new OrderEntity();
        entity.setOrderId(orderId);
        entity.setSuspendFlag(Constant.SuspendFlag.SUSPEND_STATE);
        int i = orderWriteService.updateIgnoreNull(entity);
        return i;
    }

    

    
    @Override
    public BaseResult<MemberCardRtnDTO> checkCardIdExist(String idcard,String businessCode,UserAccountVo curUser) {
        BaseResult<MemberCardRtnDTO> rstData = new BaseResult<>();


        String createTime = null;

        if (CommonUtil.invalidArgs(idcard) || !IdCardUtil.identityCardVerification(idcard).getData()) {
            throw new BizException(FailureCode.ERR_10030);
        }

        int rst = blacklistReadService.cntByIdcard(idcard);
        if(rst > 0){
            throw new BizException(FailureCode.ERR_10033);
        }


        MemberCardRtnDTO memberCardRtn = familyMemberReadService.queryMemberByCardId(idcard);
        if(null != memberCardRtn){

            String msg = packagingCardMsgNoSalvation(memberCardRtn);
            msg += "业务办理中";
            throw new BizException(FailureCode.ERR_10036.getCode(), msg);
        }


        memberCardRtn = familyMemberHistoryReadService.queryMemberHistoryByCardId(idcard);
        if(null != memberCardRtn){
            createTime = memberCardRtn.getCreateTime();

            this.dealFinishedOrder(memberCardRtn, rstData);
        }



        memberCardRtn = familyMemberReadService.queryLowerMemberByCardId(idcard);
        if(null != memberCardRtn){

            throw new BizException("-1", "该成员在低保边缘家庭认定业务办理中");
        }

        memberCardRtn = familyMemberHistoryReadService.queryLowerMemberHistoryByCardId(idcard);

            if(null != memberCardRtn && "3".equals(memberCardRtn.getStatus())){

                if(Constant.BusinessCode.TEKUN.equals(businessCode) &&
                        !(Constant.PeopleState.MARRIED.equals(memberCardRtn.getMemberState())
                                || Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(memberCardRtn.getMemberState()))
                ){

                    throw new BizException("-1", "该成员在低保边缘家庭认定通过，无法申请特困");
                }
                if (Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(memberCardRtn.getMemberState()) ||
                        Constant.PeopleState.MARRIED.equals(memberCardRtn.getMemberState())){
                    if(StringUtils.isNotEmpty(createTime)){
                        if(createTime.compareTo(memberCardRtn.getCreateTime())<0){


                            logger.info("低编分户迁出删除低保特困成员信息 参数:{},对象{}",memberCardRtn.getIdcard(),memberCardRtn);
                            familyMemberWriteService.deleteFamilyMemberByIdcard(memberCardRtn.getIdcard());

                            logger.info("低编分户迁出复制低编成员信息 参数:{},对象{}",memberCardRtn.getMemberId(),memberCardRtn);
                            familyMemberWriteService.copyMemberByMemberId(memberCardRtn.getMemberId());
                            rstData.setCode(FailureCode.ERR_10048.getCode());
                            rstData.setData(memberCardRtn);
                            rstData.setMsg("该成员在低保边缘家庭中分户迁出或嫁娶，确定要重新录入？");
                        }
                    }else{


                        logger.info("低编分户迁出删除低保特困成员信息 参数:{},对象{}",memberCardRtn.getIdcard(),memberCardRtn);
                        familyMemberWriteService.deleteFamilyMemberByIdcard(memberCardRtn.getIdcard());

                        logger.info("低编分户迁出复制低编成员信息 参数:{},对象{}",memberCardRtn.getMemberId(),memberCardRtn);
                        familyMemberWriteService.copyMemberByMemberId(memberCardRtn.getMemberId());
                        rstData.setCode(FailureCode.ERR_10048.getCode());
                        rstData.setData(memberCardRtn);
                        rstData.setMsg("该成员在低保边缘家庭中分户迁出或嫁娶，确定要重新录入？");
                    }


                } else {
                    this.refreshData(memberCardRtn);
                    int a = areaReadService.getCountByAreaCode(memberCardRtn.getAreaCode(),curUser.getAreaCode());
                    if (a == 0){
                        memberCardRtn.setAreaCode("");
                    }
                    memberCardRtn.setFamilyObjectType(Constant.MinimumLivingType.SINGLE);
                    rstData.setCode("-1");
                    rstData.setMsg("该成员在低保边缘家庭认定通过，是否录入单人保业务");
                    rstData.setData(memberCardRtn);
                    return rstData;
                }
            } else if(null != memberCardRtn && "1".equals(memberCardRtn.getStatus())){

                if(StringUtils.isNotEmpty(createTime)){

                    if(createTime.compareTo(memberCardRtn.getCreateTime())<0){
                        this.judgeLowStatus(memberCardRtn,rstData);
                    }
                }else{
                    this.judgeLowStatus(memberCardRtn,rstData);
                }
            }else {

                memberCardRtn = familyMemberReadService.queryLowerDeleteMemberByCardId(idcard);
                if (null != memberCardRtn && StringUtils.isNotEmpty(createTime)) {

                    if ( createTime.compareTo(memberCardRtn.getCreateTime()) < 0) {
                        this.judgeLowStatus(memberCardRtn,rstData);
                    }
                }else if (null != memberCardRtn){
                    this.judgeLowStatus(memberCardRtn,rstData);
                }
            }





        if(Constant.BusinessCode.DIBAO.equals(businessCode)){
            if(null == rstData.getData()){
                memberCardRtn = new MemberCardRtnDTO();
                memberCardRtn.setFamilyObjectType(Constant.MinimumLivingType.HOUSEHOLD);
                rstData.setData(memberCardRtn);
            }else{
                memberCardRtn = rstData.getData();
                memberCardRtn.setFamilyObjectType(Constant.MinimumLivingType.HOUSEHOLD);
                rstData.setData(memberCardRtn);
            }
        }
        memberCardRtn = rstData.getData();
        if(memberCardRtn != null && !StringUtils.isEmpty(memberCardRtn.getAreaCode())){
            int a = areaReadService.getCountByAreaCode(memberCardRtn.getAreaCode(),curUser.getAreaCode());
            if (a == 0){
                memberCardRtn.setAreaCode("");
                rstData.setData(memberCardRtn);
            }
        }
        return rstData;
    }

    
    private void judgeLowStatus(MemberCardRtnDTO memberCardRtn,BaseResult<MemberCardRtnDTO> rstData){
        if (Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(memberCardRtn.getMemberState())) {


            logger.info("低编分户迁出删除低保特困成员信息 参数:{},对象{}",memberCardRtn.getIdcard(),memberCardRtn);
            familyMemberWriteService.deleteFamilyMemberByIdcard(memberCardRtn.getIdcard());

            logger.info("低编分户迁出复制低编成员信息 参数:{},对象{}",memberCardRtn.getMemberId(),memberCardRtn);
            familyMemberWriteService.copyMemberByMemberId(memberCardRtn.getMemberId());
            rstData.setCode(FailureCode.ERR_10048.getCode());
            rstData.setMsg("该成员在低保边缘家庭中分户迁出，确定要重新录入？");

        } else if (Constant.PeopleState.MARRIED.equals(memberCardRtn.getMemberState())) {


            logger.info("低编嫁娶删除低保特困成员信息 参数:{},对象{}",memberCardRtn.getIdcard(),memberCardRtn);
            familyMemberWriteService.deleteFamilyMemberByIdcard(memberCardRtn.getIdcard());

            logger.info("低编嫁娶复制低编成员信息 参数:{},对象{}",memberCardRtn.getMemberId(),memberCardRtn);
            familyMemberWriteService.copyMemberByMemberId(memberCardRtn.getMemberId());
            rstData.setCode(FailureCode.ERR_10048.getCode());
            rstData.setMsg("该成员在低保边缘家庭中已嫁娶，确定要重新录入？");
        } else {
            this.refreshData(memberCardRtn);
            rstData.setCode("-1");
            rstData.setMsg("该成员曾在低保边缘录入过，确定要重新录入");
        }
        rstData.setData(memberCardRtn);
    }


    
    private void refreshData(MemberCardRtnDTO memberCardRtn){

        List<FamilyMemberEntity> memberList = familyMemberReadService.listNormalLowerByFamilyId(memberCardRtn.getFamilyId());

        for(FamilyMemberEntity familyMemberEntity1:memberList){
            FamilyMemberEntity familyMemberEntity = familyMemberReadService.getById(familyMemberEntity1.getId());
            if(familyMemberEntity != null){

                logger.info("单人保删除成员信息 参数:{},对象{}",familyMemberEntity1.getIdcard(),familyMemberEntity1);
                familyMemberWriteService.delete(familyMemberEntity1);
            }
        }
        logger.info("单人保删除家庭相关信息信息 参数:{},对象{}",memberCardRtn.getFamilyId(),memberCardRtn);

        familyMainWriteService.deleteFamilyMainById(memberCardRtn.getFamilyId());

        familyMemberWriteService.deleteFamilyMemberById(memberCardRtn.getFamilyId());

        familySupportWriteService.deleteFamilySupportById(memberCardRtn.getFamilyId());

        specialPeopleWriteService.deleteSpecialPeopleById(memberCardRtn.getFamilyId());

        familyMainWriteService.copyFamilyMainSource(memberCardRtn.getFamilyId());

        familyMemberWriteService.copyFamilyMemberSource(memberCardRtn.getFamilyId());

        familySupportWriteService.copyFamilySupportInfo(memberCardRtn.getFamilyId());

        specialPeopleWriteService.copySpecialPeopleInfo(memberCardRtn.getFamilyId());


    }



    
    private void dealUnfinishedOrder(MemberCardRtnDTO memberCardRtn, BaseResult<MemberCardRtnDTO> rstData){

        if(Constant.BizStateNew.AUDIT_REFUSE.equals(memberCardRtn.getOrderState())
                || Constant.BizStateNew.APPROVE_REFUSE.equals(memberCardRtn.getOrderState())
                || Constant.BizStateNew.TOWN_DELETE.equals(memberCardRtn.getOrderState())){
            String msg = this.packagingCardMsgNoSalvation(memberCardRtn);
//            if(Constant.DomesticRelation.ONESELF.equals(memberCardRtn.getFamilyRelation())){

            msg += "确认录入吗？";
            rstData.setCode(FailureCode.ERR_10034.getCode());
            rstData.setMsg(msg);
            rstData.setData(memberCardRtn);



//                throw new BizException(FailureCode.ERR_10035.getCode(), msg);

        }else{

            String msg = packagingCardMsgNoSalvation(memberCardRtn);
            msg += "业务办理中";
            throw new BizException(FailureCode.ERR_10036.getCode(), msg);
        }
    }
    
    private String packagingCardMsgNoSalvation(MemberCardRtnDTO memberCardRtn){

        TaDictPo businessTypeDict = dictionaryReadService.getCodeCache(DictConstant.BUSINESS_TYPE, memberCardRtn.getBusinessType());

        TaDictPo orderTypeDict = dictionaryReadService.getCodeCache(DictConstant.OPERATION_TYPE, memberCardRtn.getOrderType());

        TaDictPo orderBizStateDict = dictionaryReadService.getCodeCache(DictConstant.BIZSTATE, memberCardRtn.getOrderState());

        TaDictPo memberStateDict = dictionaryReadService.getCodeCache(DictConstant.SURVIVAL_STATUS, memberCardRtn.getMemberState());

        StringBuffer msg = new StringBuffer();
        msg.append("该人员在 ")
                .append(memberCardRtn.getCountyCode())
                .append(memberCardRtn.getStreetCode())
                .append(memberCardRtn.getAreaCode())
                .append("【")
                .append(memberCardRtn.getMasterMemberName())
                .append("】家庭中办理 ")
                .append(businessTypeDict.getLabel())
                .append(orderTypeDict.getLabel())
                .append(",")
                .append(orderBizStateDict.getLabel())
                .append(",该人员状态:");

        if(Constant.SuspendFlag.SUSPEND_STATE.equals(memberCardRtn.getSuspendFlag())){
            msg.append("业务暂停");
        }else{
            msg.append(memberStateDict.getLabel());
        }


        if(Constant.PeopleState.NORMAL.equals(memberCardRtn.getMemberState())
                && !Constant.SuspendFlag.SUSPEND_STATE.equals(memberCardRtn.getSuspendFlag())
                && Constant.BizState.APPROVE_YES.equals(memberCardRtn.getOrderState())){
            msg.append(",本月仍在救助");
        }
        return msg.toString();
    }

    
    private void dealFinishedOrder(MemberCardRtnDTO memberCardRtn, BaseResult<MemberCardRtnDTO> rstData){

        String memberState = memberCardRtn.getMemberState();
        String orderType = memberCardRtn.getOrderType();
        String orderState = memberCardRtn.getOrderState();
        if(null == memberState || null == orderType){
            throw new BizException(FailureCode.ERR_10047);
        }

        if(Constant.BizStateNew.TOWN_DELETE.equals(orderState) || Constant.BizStateNew.APPROVE_REFUSE.equals(orderState)){
            if(StringUtils.isEmpty(memberCardRtn.getSourOrderId())){

                String msg = packagingCardMsgNoSalvation(memberCardRtn);
                msg += "确认录入吗？";
                rstData.setCode(FailureCode.ERR_10034.getCode());
                rstData.setMsg(msg);
                rstData.setData(memberCardRtn);
                return;
            }else{

                FamilyMemberHistoryEntity familyMemberHistoryEntity = familyMemberHistoryReadService.getBySourOrderId(memberCardRtn.getMemberId(),memberCardRtn.getSourOrderId());

                if (null == familyMemberHistoryEntity){

                    String msg = packagingCardMsgNoSalvation(memberCardRtn);
                    msg += "确认录入吗？";
                    rstData.setCode(FailureCode.ERR_10048.getCode());
                    rstData.setMsg(msg);
                    rstData.setData(memberCardRtn);
                    return;
                } else {
                    if(Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(memberState)){
                        String msg = this.packagingCardMsgCanSavation(memberCardRtn);
                        msg += "原因是：分户迁出,确定要重新录入？";

                        rstData.setCode(FailureCode.ERR_10048.getCode());
                        rstData.setMsg(msg);
                    }else if(Constant.PeopleState.MARRIED.equals(memberState)){
                        String msg = this.packagingCardMsgCanSavation(memberCardRtn);
                        msg += "原因是：嫁娶,确定要重新录入？";

                        rstData.setCode(FailureCode.ERR_10048.getCode());
                        rstData.setMsg(msg);
                    }else {

                        String msg = packagingCardMsgNoSalvation(memberCardRtn);
                        msg += "。上条业务生效中，不能重新录入";
                        throw new BizException(FailureCode.ERR_10036.getCode(), msg);
                    }
                }
            }



        }
        

        SimpleDateFormat sdf  =new SimpleDateFormat("yyyyMM");
        boolean rst = false;
        try {
            if(StringUtils.isEmpty(memberCardRtn.getEndMonth())){
                rst = true;
            }else{
                Date dateD = sdf.parse(memberCardRtn.getEndMonth());
                String todayD = sdf.format(new Date());
                Date todayF= sdf.parse(todayD);
                rst = dateD.getTime() < todayF.getTime();
            }


        } catch (ParseException e1) {
            e1.printStackTrace();
        }


        if(Constant.PeopleState.DEAD.equals(memberState) || (Constant.PeopleState.NORMAL.equals(memberState)) ||
                (Constant.SuspendFlag.SUSPEND_STATE.equals(memberCardRtn.getSuspendFlag())
                        && !Constant.OrderType.EXPIRE.equals(orderType))){
            
                throw new BizException(FailureCode.ERR_10037.getCode(), packagingCardMsgNoSalvation(memberCardRtn));


        }

        if(!Constant.OrderType.EXPIRE.equals(orderType) && !Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(memberState)
                && !Constant.PeopleState.MARRIED.equals(memberState)){

            int isHouseHoldCancel =  familyMemberReadService.selectHouseholdSuspendByHistory(memberCardRtn.getOrderId());
            if(isHouseHoldCancel>0){
                if(!Constant.PeopleState.DEAD.equals(memberState)){


                    OrderEntity sourceOrder = orderReadService.getById(memberCardRtn.getSourOrderId());

                    try {
                        Date nowDate = new Date();

                        Date endMonth = DateUtil.sdf2.parse(sourceOrder.getEndMonth());
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(endMonth);
                        calendar.add(Calendar.MONTH,1);
                        Date effectMonth = calendar.getTime();
                        if(nowDate.before(effectMonth)){
                            String msg = packagingCardMsgNoSalvation(memberCardRtn);
                            msg += "生效年月为"+DateUtil.sdfYM.format(effectMonth)+";当前不能录入";
                            rstData.setCode(FailureCode.ERR_10034.getCode());
                            rstData.setMsg(msg);
                            rstData.setData(memberCardRtn);
                            throw new BizException("-1", msg);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    String msg = packagingCardMsgNoSalvation(memberCardRtn);
                    msg += "确认录入吗？";
                    rstData.setCode(FailureCode.ERR_10034.getCode());
                    rstData.setMsg(msg);
                    rstData.setData(memberCardRtn);
                    return;
                }
            }
            String msg = packagingCardMsgNoSalvation(memberCardRtn);
            msg += "，如需继续救助，可去原家庭恢复";
            if(!Constant.PeopleState.NORMAL.equals(memberState)){
                throw new BizException(FailureCode.ERR_10035.getCode(), msg);
            }

        }

        if(Constant.OrderType.EXPIRE.equals(orderType) && Constant.PeopleState.EXPIRE.equals(memberState)){
            String msg = this.packagingCardMsgCanSavation(memberCardRtn);
            msg += "确认录入吗？";
            rstData.setCode(FailureCode.ERR_10034.getCode());
            rstData.setMsg(msg);
        }else if(Constant.PeopleState.MOVE_OUT_HOUSEHOLD.equals(memberState)){
            String msg = this.packagingCardMsgCanSavation(memberCardRtn);
            msg += "原因是：分户迁出,确定要重新录入？";

            rstData.setCode(FailureCode.ERR_10048.getCode());
            rstData.setMsg(msg);
        }else if(Constant.PeopleState.MARRIED.equals(memberState)){
            String msg = this.packagingCardMsgCanSavation(memberCardRtn);
            msg += "原因是：嫁娶,确定要重新录入？";

            rstData.setCode(FailureCode.ERR_10048.getCode());
            rstData.setMsg(msg);
        }
        if((Constant.PeopleState.NORMAL.equals(memberState)) && rst){
            String msg = this.packagingCardMsgCanSavation(memberCardRtn);
            msg += "确认录入吗？";
            rstData.setCode(FailureCode.ERR_10034.getCode());
            rstData.setMsg(msg);
        }
        rstData.setData(memberCardRtn);
    }

    
    private String packagingCardMsgCanSavation(MemberCardRtnDTO memberCardRtn){

        TaDictPo businessTypeDict = dictionaryReadService.getCodeCache(DictConstant.BUSINESS_TYPE, memberCardRtn.getBusinessType());

        StringBuffer msg = new StringBuffer();
        msg.append("该人员在 ")
                .append(memberCardRtn.getCountyCode())
                .append(memberCardRtn.getStreetCode())
                .append(memberCardRtn.getAreaCode())
                .append("【")
                .append(memberCardRtn.getMasterMemberName())
                .append("】家庭 ")
                .append(businessTypeDict.getLabel())
                .append(",保障")
                .append(memberCardRtn.getEndMonth())
                .append("时间停保。");
        return msg.toString();
    }

    
    private  boolean checkifHasNormState(String orderId) {
        boolean flag = false;

        List<FamilyMemberDTO> memberList = familyMemberReadService.listMemberByOrderId(orderId);
        for (FamilyMemberDTO member : memberList) {
            if (member.getState().equals(Constant.PeopleState.NORMAL)) {
                flag = true;
                break;
            }
        }
        return  flag;
    }
    
    @Override
    public void verifyOrderNoReason(String orderId){
        int i = orderReadService.selectOrderNoReason(orderId);
        if(i>0){
            throw new BizException("-1","复查原因为空，请在编辑页面填写复查原因。");
        }
    }

}
